package com.example.qihuibao.network;

import com.example.qihuibao.constant.Config;
import com.example.qihuibao.utils.LogUtil;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Create by cm132 on 2019/11/13 17:31.
 * Describe:网络请求
 */
public class RetrofitManager {

	private volatile static RetrofitManager instance;
	private Retrofit retrofit;
	private RetrofitApi retrofitApi;

	private RetrofitManager() {
		HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
			@Override
			public void log(String message) {
				//打印retrofit日志
				LogUtil.INSTANCE.e("HttpLog: " + message);
			}
		});
		loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

		OkHttpClient okHttpClient = new OkHttpClient.Builder()
				.readTimeout(10, TimeUnit.SECONDS)
				.connectTimeout(10, TimeUnit.SECONDS)
				.addInterceptor(loggingInterceptor)
				.build();

		retrofit = new Retrofit.Builder()
				.client(okHttpClient)
				.baseUrl(Config.INSTANCE.getSERVER_BASE_URL())
				.addConverterFactory(GsonConverterFactory.create())
				.build();

		retrofitApi = create(RetrofitApi.class);
	}

	public static RetrofitManager getInstance() {
		if (instance == null) {
			synchronized (RetrofitManager.class) {
				if (instance == null) {
					instance = new RetrofitManager();
				}
			}
		}
		return instance;
	}


	public <T> T create(Class<T> api) {
		return retrofit.create(api);
	}

	public void resetRetrofit() {
		instance = null;
	}

	public RetrofitApi getHttpApi() {
		return retrofitApi;
	}
}
